package com.gzhryc.shared_device.iot.core.aliyun.models;

import com.aliyuncs.iot.model.v20180120.RRpcResponse;
import com.gzhryc.shared_device.iot.core.IOTMessage;
import com.gzhryc.shared_device.iot.core.IOTSynResponse;
import org.apache.commons.lang3.StringUtils;

import java.util.Base64;

public class AliyunIOTSynResponse extends IOTSynResponse {

	private static final long serialVersionUID = 1L;
	
	protected final RRpcResponse response;
	
	public AliyunIOTSynResponse(RRpcResponse response) {
		this.response = response;
	}

	public RRpcResponse getResponse() {
		return response;
	}

	@Override
	public Boolean isSuccess() {
		return response.getSuccess() && "SUCCESS".contains(response.getRrpcCode());
	}
	
	@Override
	public Boolean isTimeout() {
		return "TIMEOUT".equals(response.getRrpcCode());
	}

	@Override
	public Integer getCode() {
		return null;
	}

	@Override
	public <T extends IOTMessage> T getMessage(Class<T> clazz) {
		if(response != null) {
			try {
				T msg = clazz.newInstance();
				msg.setBytes(Base64.getDecoder().decode(response.getPayloadBase64Byte()));
				return msg;
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public IOTMessage getMessage() {
		if(response != null && StringUtils.isNotBlank(response.getPayloadBase64Byte())) {
			IOTMessage msg = new IOTMessage();
			msg.setBytes(Base64.getDecoder().decode(response.getPayloadBase64Byte()));
			return msg;
		}
		return null;
	}
}
